package xyz.kongbai121.drawingbed.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.Getter;
import lombok.Setter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;
import xyz.kongbai121.drawingbed.constant.DrawingBedConstant;
import xyz.kongbai121.drawingbed.utils.R;
import xyz.kongbai121.drawingbed.vo.UserVo;

import java.util.UUID;
import java.util.concurrent.TimeUnit;


@RestController
@Api(tags = "用户控制器")
@RequestMapping("/api/user")
@ConfigurationProperties(prefix = "drawing-bed.user")
public class LoginController {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Setter @Getter
    private String usernameYml;

    @Setter @Getter
    private String passwordYml;


    @ApiOperation(value = "登录(token有效期30分钟)", notes = "")
    @PostMapping("/login")
    public R login(@RequestBody UserVo userVo){
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        //密码匹配
        boolean matches = passwordEncoder.matches(userVo.getPassword(), passwordYml);
        //账号密码正确
        if (usernameYml.equals(userVo.getUsername()) && matches){
            String token = UUID.randomUUID().toString().replace("-", "");
            redisTemplate.opsForValue().set(DrawingBedConstant.TOKEN_PREFIX + token, "暂时啥也不存", 30, TimeUnit.MINUTES);
            return R.ok().setData(token);
        }
        return R.error(5555,"账号或密码错误");
    }

    @ApiOperation(value = "token续期(30分钟)", notes = "")
    @PostMapping("/renewal")
    public R renewal(@ApiParam(value = "将要续期的token", required=true) @RequestParam("token") String token){
        redisTemplate.expire(DrawingBedConstant.TOKEN_PREFIX + token,2,TimeUnit.HOURS);
        return R.ok();
    }


}
